package com.threadlocal.pool.socket;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.net.Socket;

public class HandleSocket {
	public static void handleoutput(Socket socket) {
		InputStream in = null;
		OutputStream out = null;
		try {
			in = socket.getInputStream();
			out = socket.getOutputStream();

			BufferedReader br = getReader(socket);
			PrintWriter pw = getWriter(socket);
			
			

			BufferedReader r = new BufferedReader(new InputStreamReader(
					System.in));

			String line=r.readLine();
			if("bye"!=line){
				pw.print(line);
				System.out.println(br.readLine());
				line=r.readLine();
			}
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

	}

	private static BufferedReader getReader(Socket socket) {

		BufferedReader br = null;
		try {
			br = new BufferedReader(new InputStreamReader(
					socket.getInputStream()));
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return br;
	}

	private static PrintWriter getWriter(Socket socket) {

		PrintWriter pw = null;
		try {
			pw = new PrintWriter((socket.getOutputStream()));
		} catch (IOException e) {
			e.printStackTrace();
		}
		return pw;
	}

	public static void handleInput(Socket socket) {
		System.out.println("welcome::" + socket.getLocalSocketAddress());
		InputStream in = null;
		OutputStream out = null;
		try {
			in = socket.getInputStream();
			out = socket.getOutputStream();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

		BufferedReader reader = new BufferedReader(new InputStreamReader(in));
		PrintWriter print = new PrintWriter(out);
		String line = null;
		try {
			line = reader.readLine();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

		StringBuffer sb = new StringBuffer();
		while (line != null) {

			System.out.println(line.toString());
			sb.append(line.toString());
			print.print(sb.toString());
			if (line.toString().equals("exit")) {
				try {
					in.close();
					reader.close();
					line = null;

				} catch (IOException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}
			try {
				line = reader.readLine();
			} catch (IOException e) {

			}
		}

	}
}
